package com.gmq.javaMulti.chapter02;

/**
 * Created by gmq on 2018/10/07.
 * volatile 并不能真正保证线程安全，只能确保一个线程修改了数据后，其他线程能够看到这个改动
 * @version 1.0
 * @since 2018/10/07 14:52
 */
public class AccountingSyncBad implements Runnable {
    static AccountingSyncBad instance = new AccountingSyncBad();
    static volatile int i = 0;

    /*public synchronized void increase() {
        i++;
    }*/

    public synchronized static void increase() {
        i++;
    }

    @Override
    public void run() {
        for (int j = 0; j < 10000000; j++) {
            //synchronized (instance) {
                increase();
            //}
        }
    }

    public static void main(String[] args) throws InterruptedException {
//        Thread t1 = new Thread(instance);
//        Thread t2 = new Thread(instance);

        Thread t1 = new Thread(new AccountingSyncBad());
        Thread t2 = new Thread(new AccountingSyncBad());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);
    }
}
